<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\tool\Result;
use think\facade\View;
use think\Response;
use think\response\Json;
use addons\Builder\facade\Builder;
use app\common\model\Logs;
use app\common\model\Cate;
use app\common\model\UserCourse;
use think\exception\ValidateException;
use addons\Gallery\driver\Gallery;

class User extends Base
{
    protected string $pk = 'id';

    protected string $validate = 'User';

    protected string $model = '\app\common\model\User';

    protected $append = ['sexText', 'cateText'];

    protected array $sort = [
        'ordinary' => [
            'create_time' => 'desc'
        ],
        'formal'   => [
            'active_time' => 'desc'
        ]
    ];
    public function formal(): string
    {
        return $this->fetch([], [], ['is_active', '=', 2]);
    }

    public function fetch($rb = [], $tb = [], $extra_map = []): string
    {

        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,' . ($rb ? '190' : '140'), false)
            ->addRightButtons(
                array_merge([
                    'edit'  => ['size' => '50%'],
                    'delete'
                ], $rb)
            )
            ->addTopButtons(
                array_merge($tb, [
                    'add' => ['size' => '80%'],
                    'reset_1' => [
                        'title'       => '重置登录密码',
                        'placeholder' => '请填写新密码，默认111111',
                        'icon'        => 'layui-icon-password',
                        'url'         => url('user/reset', ['type' => 1])->build(),
                        'event'       => '_batchPrompt'
                    ],
                    'export'
                ])
            )
            ->addExtraMap([$extra_map])
            ->addSearch([
                ['code__rname__mobile', '会员编号/姓名/手机号', 'input,Like']
            ])
            ->fetch();
    }
    public function add($tpl = 'user/add')
    {
        $cate = Cate::where('pid',0)->order('sort asc')->select();
        $qn_token= Gallery::getQnList();
        view::assign(
            [
                'cate' => $cate,
                'qn_token'=>$qn_token['token'],
                'qn_url'=>$qn_token['url'],
                'domain_url'=>$qn_token['domain'],
            ]
        );
        return parent::add($tpl); // TODO: Change the autogenerated stub
    }

    public function edit($id = '', $tpl = 'user/edit', $info = '')
    {
        $cate = Cate::where('pid',0)->order('sort asc')->select();
        // foreach($cate as &$v){
        //     $count= UserCourse::where(['uid'=>$id,'cate_id'=>$v->id])->count();
        //     if($count>0){
        //         $v->check = true;
        //     }else{
        //         $v->check = false;
        //     }
        // }
        view::assign(
            [
                'cate' => $cate
            ]
        );
        return parent::edit($id, $tpl, $info); // TODO: Change the autogenerated stub
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($this->request->post(), $model); // TODO: Change the autogenerated stub
    }

    public function reset($type): Response
    {
        try {
            $ids = $this->request->post('ids');
            $pass = $this->request->post('pass');
            if ($type == 1) {
                $key = 'password';
                $value = md5($pass ?: '111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5($pass ?: '222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return Result::success('已重置');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }


    public function login($id): Response
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return Result::fastReturn(['code' => 1, 'msg' => '登录成功', 'data' => ['code' => $user->code, 'url' => '/']]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    public function delete(): Response
    {
        try {
            $user = $this->model::where('id', $this->request->post($this->pk))->find();
            if (empty($user)) {
                return Result::fail('会员不存在');
            }
            $this->model::destroy(['id' => $user->id]);

            Logs::adds('删除会员【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);
            return Result::success('已删除');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
